package com.meila.cms.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.meila.cms.auth.AuthClass;
import com.meila.cms.common.basic.util.MatrixToImageWriter;
import com.meila.cms.common.constants.AttachmentConstants;
import com.meila.cms.common.page.SystemContext;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Hashtable;

@RequestMapping("/admin/qr")
@Controller
@AuthClass
public class QRController {
	
	@RequestMapping("/create")
	public String getMapLine() {
		return "qr/create";
	}


	public JSONObject createQR(JSONObject obj) throws IOException, WriterException, JSONException {

		//扫描的url
		String url = obj.optString("url");
		//生成的二维码宽度
		int width = obj.optInt("width");
		//生成的二维码高度
		int height = obj.optInt("height");
		//生成的二维码的图片格式
		String suffix = obj.optString("suffix");

		Hashtable hints = new Hashtable();
		//内容所使用编码
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
		//生成二维码
		String name = String.valueOf(new Date().getTime()) + "." + suffix;
		//进行文件的存储
		String realPath = SystemContext.getRealPath();
		//附件上传的路径
		String path = realPath + AttachmentConstants.UPLOADPATH;
		File outputFile = new File(path + name);
		MatrixToImageWriter.writeToFile(bitMatrix, suffix, outputFile);
		//返回结果
		JSONObject result = new JSONObject();
		result.put("name", name);
		result.put("url", url);
		result.put("weight", width);
		result.put("height", height);
		result.put("suffix", suffix);
		return result;

	}

	

	
}
